<template>
  <Modal
    id="resourceCheckBoxsDialog"
    v-model="initOption.visible"
    :mask-closable="false"
    @on-cancel="onModalCancel"
    width="800">
    <p slot="header" style="color:#f60;text-align:center;">
      <Icon type="information-circled"></Icon>
      <span>授权资源</span>
    </p>
    <Card v-for="s in resList" :key="s.value">
      <p slot="title">{{s.title}}</p>
      <Card v-for="(m, index) in s.children" :key="m.value">
        <p slot="title">{{m.title}}</p>
        <Checkbox-group v-model="currentValue">
          <Checkbox :label="r.value" v-for="r in m.children" :key="r.value">
            <span>{{r.title}}</span>
          </Checkbox>
        </CheckBox-group>
      </Card>
    </Card>
    <div slot="footer">
      <Button type="primary" @click="handleSubmit">保存</Button>
    </div>
  </Modal>
</template>
<script>
import {getResourceTreeInfo} from '@/apis/admin/resource';
import {getRoleInfo, grantResource} from '@/apis/admin/role';

export default {
  name: 'resourceCheckBoxsDialog',
  props: {
    initOption: {
      visible: {
        type: Boolean,
        default: false
      },
      roleId: {
        type: String,
        default: null
      },
      orgId: {
        type: String,
        default: null
      }
    }
  },
  data: function data () {
    return {
      resList: [],
      currentValue: []
    };
  },
  methods: {
    getResList: function getResList () {
      getResourceTreeInfo().then(response => {
        let obj = response.data;
        if (obj.success) {
          this.resList = obj.obj;
          this.getChecked();
        }
      });
    },
    getChecked () {
      getRoleInfo(this.initOption.roleId).then(response => {
        let obj = response.data;
        if (obj.success) {
          this.currentValue = obj.obj.rids.split(',') || [];
        }
      });
    },
    handleSubmit () {
      grantResource(this.initOption.roleId, this.currentValue.join()).then(response => {
        let obj = response.data;
        if (obj.success) {
          this.$parent.roleResourceCheckBoxInitOption.visible = false;
          this.$Notice.success({
            title: '提示',
            desc: response.data.msg
          });
        } else {
          this.$Notice.error({
            title: '提示',
            desc: response.data.msg
          });
        }
      });
    },
    onModalCancel () {
      this.currentValue = [];
    }
  },
  computed: {
  },
  watch: {
    'initOption.visible' (val) {
      if (val) {
        this.getResList();
      } else {
        this.resList = [];
      }
    }
  }
};
</script>
<style>
</style>
